import { DataSource } from 'typeorm';
import * as yaml from 'js-yaml';
import * as fs from 'fs';
import { join } from 'path';

const configFilenameMap = {
  development: 'dev.config.yaml',
  production: 'prod.config.yaml'
}

const YAML_CONFIG_FILENAME = configFilenameMap[process.env.NODE_ENV] || 'prod.config.yaml';
const configFilePath = join(process.cwd(), 'assets', YAML_CONFIG_FILENAME);
const config = yaml.load(fs.readFileSync(configFilePath, 'utf8')) as Record<string, any>;

export default new DataSource({
  type: 'mysql',
  host: config.database.host,
  port: config.database.port,
  username: config.database.username,
  password: config.database.password,
  synchronize: false,
  database: config.database.database,
  logging: true,
  entities: [`${__dirname}/**/*.entity{.ts,.js}`],
  migrations: [`${__dirname}/**/migrations/*{.ts,.js}`],
  migrationsTableName: 'migrations_heart_ai',
  timezone: '+08:00',
  dateStrings: true,
});
